package com.oxygen.utils.file;

import com.oxygen.utils.entity.JsonResponse;
import com.oxygen.utils.uuid.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
//JsonResponse<Map<String,Object>>
@Controller
@RequestMapping("/back/commodity")
public class FileUpload {
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    @ResponseBody
    public JsonResponse<Map<String,Object>> uploadFile(MultipartFile file) throws IOException {
        JsonResponse<Map<String,Object>> jsonResponse = new JsonResponse<>();
        if(file != null && StringUtils.isNotBlank(file.getOriginalFilename()) && file.getOriginalFilename().length()>0){
            String rootPath = System.getProperty("webapp.root");
            String storePath = new File(rootPath).getParentFile().getParent();
            String extra = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            String fileName = UUIDUtil.getUUID()+extra;
            String filePath = storePath + "/src/main/webapp/static/upload/";
            File targetFile = new File(filePath);
            if(!targetFile.exists()){
                targetFile.mkdirs();
            }
            filePath += fileName;
            System.out.println(filePath);
            file.transferTo(new File(filePath));
            jsonResponse.setError(false);
            jsonResponse.setMsg("上传成功");
            Map<String,Object> data = new HashMap<>();
            data.put("imgUrl", fileName);
            jsonResponse.setData(data);
        }
        return jsonResponse;
    }

}
